package org.bdware.doip.endpoint.doipClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.bdware.doip.core.codec.packet.PacketNettyTCPCodec;
import org.bdware.doip.core.codec.packet.PacketNettyWSCodec;
import org.bdware.doip.core.utils.GlobalConfigurations;

import java.net.URI;
import java.net.URISyntaxException;

public class NettyDoipWSClientChannel extends NettyDoipClientChannel {

    final Bootstrap b = new Bootstrap();
    EventLoopGroup group;

    public NettyDoipWSClientChannel() {
    }

    @Override
    public void close() {
        if(handler != null) handler.close();
        isConnected = false;
    }

    @Override
    public void connect(String targetUrl) throws URISyntaxException {
        URI uri = new URI(targetUrl);
        logger.debug("[URI Parse]target URI:" + uri.toString());
        if(group == null){
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
            group = new NioEventLoopGroup();

            b.group(group);
            handler = new NettyDoipClientHandler();
            b.channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(
                            new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel ch) {
                                    ch.pipeline()
                                            //基于HTTP
                                            .addLast(new HttpClientCodec())
                                            .addLast(new HttpObjectAggregator(GlobalConfigurations.defaultMsgMTU))
                                            .addLast(new WebSocketClientProtocolHandler(
                                                    WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())))
                                            .addLast(new PacketNettyWSCodec())
                                            .addLast(handler);
                                }
                            });
            logger.info("[DoipClient] Create WS Client!");
        }
        try {
            logger.debug("[URI Parse]host: "+ uri.getHost() + "  port: " + uri.getPort());
            channel = b.connect(uri.getHost(), uri.getPort()).sync().channel();
            handler.setChannel(channel);
        }catch (Exception e){
            e.printStackTrace();
        }
        isConnected = true;
    }

}
